package com.bdmc.smokesensor.services;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.bdmc.smokesensor.Utils.CommonUtil;
import com.bdmc.smokesensor.dao.Rbac_RoleJPA;
import com.bdmc.smokesensor.entity.Rbac_Role;
import com.bdmc.smokesensor.iservices.IRbac_RoleService;
import com.bdmc.smokesensor.models.zTreeList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

@Service
public class Rbac_RoleService extends BaseService<Rbac_Role> implements IRbac_RoleService {

    @Autowired
    private Rbac_RoleJPA _roleJPA;

    @Override
    public List<Rbac_Role> findAll() {
        List<Rbac_Role> list = _roleJPA.findAll();
        return list;
    }

    @Override
    public List<Rbac_Role> findByTreeRoot(int dep_id) {
        List<Rbac_Role> list = _roleJPA.findBytreeRoot(dep_id,","+dep_id+",");
        return list;
    }

    @Override
    public Map<String,Object> findBySqlPageable(int page, int rows){
        Page<Rbac_Role> p = _roleJPA.findAll( PageRequest.of(page,rows));
        Map<String,Object> map = new HashMap<String,Object>();
        map.put("total", p.getTotalElements());
        map.put("data", p.getContent());
       return map; 
    }

    @Override
    public Rbac_Role findOne(Example<Rbac_Role> example) {
        return _roleJPA.findOne(example).orElse(null);
    }

    @Override
    public Rbac_Role findOneById(int id) {
        return _roleJPA.findById(id).orElse(null);
    }

    @Override
    public Rbac_Role save(Rbac_Role d) {
        if (d.getId() < 1)
            d.setJoinDate(new Date());
        else
            d.setUpdateDate(new Date());
        return _roleJPA.save(d);
    }

    @Override
    public void deleteById(int id) {
        _roleJPA.deleteById(id);
    }

    @Override
    public List<zTreeList> GetzTreeListByRoleId(int userRoleId) {
       List<zTreeList> re = new ArrayList<zTreeList>();
       List<Object[]>  lo =_roleJPA.GetzTreeListByRoleId(userRoleId);
        try {
            re = CommonUtil.castEntity(lo, zTreeList.class); 
        } catch (Exception e) {
            System.out.println("error:"+e.toString());
        }
        return re;
    }

    @Override
    public List<zTreeList> GetActionListByRoleId(int userRoleId) {
       List<zTreeList> re = new ArrayList<zTreeList>();
       List<Object[]>  lo =_roleJPA.GetzActionListByRoleId(userRoleId);
        try {
            re = CommonUtil.castEntity(lo, zTreeList.class); 
        } catch (Exception e) {
            System.out.println("error:"+e.toString());
        }
        return re;
    }
}